<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/22
 * Time: 16:02
 */

namespace app\api\controller;


use app\api\model\Admin;

use app\api\model\Gold as GoldModel;
use app\api\model\ReceiveTask as ReceiveModel;
use app\api\model\Recommend as RecommendModel;
use app\api\model\Task as TaskModel;
use app\api\model\User as UserModel;
use app\api\service\Task as TaskService;
use app\api\service\User as UserService;
use think\Db;

class Task
{
    /**
     * 发布任务
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $user_id = UserService::getUserIdByToken();
        $need = input('need');
//        $duration = input('duration');
        //TODO 参数判断  正整数
        if(!is_numeric($need)||strpos($need,".")!==false || $need <=0){
            return json(['errorCode' => 1, 'msg' => '招募人数必须大于0 ']);
        }
        $user = UserModel::get($user_id)->visible([]);
        //判断是否为发包方
        if ($user['level'] != 1 && $user['level'] != 2) {
            return json(['errorCode' => 1, 'msg' => '您没有发包资格']);
        }
        //获取保证金比例
//        $bond = Db::name('config_param')->where('key', 'bond')->value('value');
        //计算冻结金币,冻结金币改成扣除金币
//        $task_gold = ceil($need + $need * $bond);
        $task_gold = $need;

        //判断金币余额
        if ($user['gold'] < $task_gold) {
            return json(['errorCode' => 0, 'msg' => '可用金币不足', 'data' => false]);
        }
        if (empty($user['wechat_id'])) {
            return json(['errorCode' => 1, 'msg' => '请先绑定任务微信信息']);
        }
        (new UserModel())->where('id', $user_id)->setDec('gold', $task_gold);

        $data = [
            'number' => generate_task_no(),//调用生成编号函数
            'user_id' => $user_id,
            'wechat_id' => $user['wechat_id'],//微信号
            'need' => $need,
            'status' => 0,
//            'end_time' => strtotime($duration),
            'update_time' => time(),
            'add_time' => time()
        ];
        $res = TaskModel::create($data);
        if (!$res) {
            return json(['errorCode' => 1, 'msg' => '任务创建失败']);
        }
//        (new UserModel())->where('id', $user_id)->setInc('task_time');
        //记录金币日志
        //发布日志时扣除
//        $user->gold = $user['gold'] - $task_gold;
//        $user->save();
        $gold_log = [
            'title' => '发布任务【' . $data['number'] . '】扣除',
            'type' => -1,
            'user_id' => $user_id,
            'task_id' => $res['id'],
            'amount' => $task_gold,
            'add_time' => $data['add_time']
        ];
        $g = GoldModel::create($gold_log);
        return json(['errorCode' => 0, 'msg' => '任务创建成功', 'data' => ['number' => $data['number']]]);

    }

    /**
     * 获取列表
     * @param int $page
     * @param int $size
     * @return \think\response\Json
     */
    public function getList($page = 1, $size = 20)
    {
        $user_id = UserService::getUserIdByToken();
        //过滤已领过任务所发布的用户的任务
        $task_user_ids = ReceiveModel::where('user_id', $user_id)->column('task_user_id');
        if ($task_user_ids) {
            $cond['user_id'] = ['not in', $task_user_ids];
        }
        $cond['status'] = config('status.任务_未完成');

        $list = TaskModel::where($cond)->where('receive < need')->with('user')->page($page, $size)->order(['update_time' => 'desc'])->select();
        return json(['errorCode' => 0, 'data' => $list]);
    }


    //获取个人任务列表
    public function getPersonalList()
    {
        $user_id = UserService::getUserIdByToken();
        $list = TaskModel::where('user_id', $user_id)->order('status asc ,update_time desc')->select();
        foreach ($list as &$item) {
            $gold = TaskService::refreshNeedGold($item['id'], $user_id);
            $item['gold'] = $gold;
        }
        return json(['errorCode' => 0, 'msg' => '个人任务列表', 'data' => $list]);
    }

    /**
     * 任务详情
     * @param $task_id
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function detail($task_id)
    {
        $visible = [];
//        $info = TaskModel::getOne($task_id, $visible);
        $info = TaskModel::with('user')->find($task_id);
        return json(['errorCode' => 0, 'data' => $info]);
    }

    /**
     * 接收任务
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function receive()
    {
        //判断当日所领取任务数量
        $user_id = UserService::getUserIdByToken();
        $task_id = input('task_id');
        //判断用户是否已经领过该用户发布的任务
        $task_user_id = TaskModel::where('id', $task_id)->value('user_id');
        $receive_id = ReceiveModel::where(['task_user_id' => $task_user_id, 'user_id' => $user_id])->value('id');
        if ($receive_id) {
            return json(['errorCode' => 1, 'msg' => '您已经领取过该脉粉发布的任务,请选别其他脉粉发布的任务']);
        }
        $user = UserModel::get($user_id);
        if (!UserService::checkDailyTaskTime($user)){
            return json(['errorCode' => 0, 'msg' => '您已达到当日领取任务次数上限', 'data' => ['type' => '2']]);
        }
        /*if ($user['level'] == 0 && $user['task_time'] >= 3) {
            return json(['errorCode' => 0, 'msg' => '您已达到当日领取任务次数上限', 'data' => ['type' => '2']]);
        }
        if ($user['level'] == 1 && $user['task_time'] >= 10) {
            return json(['errorCode' => 0, 'msg' => '您已达到当日领取任务次数上限', 'data' => ['type' => '2']]);
        }
        if ($user['level'] == 2 && $user['task_time'] >= 20) {
            return json(['errorCode' => 0, 'msg' => '您已达到当日领取任务次数上限', 'data' => ['type' => '2']]);
        }*///判断任务次数限制
        $task = TaskModel::get($task_id);
        if ($task['user_id'] == $user_id) {
            return json(['errorCode' => 1, 'msg' => '您不能领取自己发布的任务']);
        }
        if (ReceiveModel::get(['user_id' => $user_id, 'task_id' => $task_id])) {
            return json(['errorCode' => 1, 'msg' => '您已经领取过该任务']);
        }
        if ($task['status'] == 1) {
            //todo  返回0
            return json(['errorCode' => 0, 'msg' => '任务已完成', 'data' => ['type' => 3]]);//任务结束
        }
        if ($task['need'] <= $task['receive']) {
            //todo  返回0
            return json(['errorCode' => 0, 'msg' => '计划招募粉丝数已满', 'data' => ['type' => 3]]); //任务结束
        }
//        if ($task['end_time'] < time()) {
//            //TODO 改变任务状态
//            return json(['errorCode' => 1, 'msg' => '该任务已结束']);
//        }
        //生成code
        $code = generate_code(6);
        $data = [
            'code' => $code,
            'user_id' => $user_id,
            'task_user_id' => $task['user_id'],
            'task_id' => $task_id,
            'status' => 0,
            'add_time' => time()
        ];
        $res = ReceiveModel::create($data);
        if (!$res) {
            return json(['errorCode' => 1, 'msg' => '接收任务失败']);
        }
        //获取发布任务者信息
        $t_user = UserModel::get($task['user_id']);
        //更改已招募人数,更改领取次数
        $task->receive = $task['receive'] + 1;
        $task->save();
        TaskService::operationWaitMoney($user);
        /*//增加待结算
        $user->task_time = $user['task_time'] + 1;
        $user->wait_money = $user['wait_money'] + config('config.任务_完成奖励金额');
        $user->save();
        //增加上级待结算金额
        UserModel::where('id', $user['parentid'])->setInc('wait_money', config('config.任务_完成一级推荐奖')); //待结算
        //增加脉大师待结算金额
        $promoter_id = RecommendModel::getPromoterID($user_id);
        UserModel::where('id', $promoter_id)->setInc('wait_money', config('config.任务_完成一级推荐奖'));//待结算*/
        //拼接返回数据
        $res['type'] = 1;//成功
        $res['nickname'] = $t_user['nickname'];
        $res['wechat_id'] = $t_user['wechat_id'];
        $res['avatar'] = $t_user['avatar'];
        $res['wechat_qrcode'] = $t_user['wechat_qrcode'];
        return json(['errorCode' => 0, 'msg' => '接收任务成功', 'data' => $res]);
    }

    //接收任务列表
    public function receiveList($status = '', $page = 1, $size = 20)
    {
        $user_id = UserService::getUserIdByToken();
        $cond['user_id'] = $user_id;
        $cond['status'] = $status;
        $list = ReceiveModel::where($cond)->with('task_user.user')->page($page, $size)->order('add_time desc')->select();
        return json(['errorCode' => 0, 'data' => $list]);
    }

    /**
     * 获取任务粉丝列表
     * @param $task_id
     * @param $user_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fansList($task_id, $code = '', $page = 1, $size = 20)
    {
        $user_id = UserService::getUserIdByToken();
        if (!TaskService::checkUser($task_id, $user_id)) {
            return json(['errorCode' => 1, 'msg' => '您无权查看此任务的粉丝列表']);
        }
        $where['task_id'] = $task_id;
        if (!empty($code)) {
            $where['code'] = ['like', '%' . $code . '%'];
        }
        $list = ReceiveModel::where($where)->with('user')->field('')->page($page,$size)->order('status asc ,add_time desc')->select();
        return json(['errorCode' => 0, 'data' => $list]);
    }

    //任务粉丝确认
    public function checkFans($id)
    {
        $user_id = UserService::getUserIdByToken();
        $receive = ReceiveModel::get($id);
//        dump($receive);
//        $receive->visible();
        if (!$receive) {
            return json(['errorCode' => 1, 'msg' => '任务参数错误']);
        }
        $receive_user_id = $receive['user_id'];
        $task_id = $receive['task_id'];
        if (!TaskService::checkUser($task_id, $user_id)) {
            return json(['errorCode' => 1, 'msg' => '这不是您发布的任务']);
        }
        if ($receive['status'] == config('status.接收任务_已结算')) {
            return json(['errorCode' => 1, 'msg' => '该粉丝已结算']);
        }
        $receive->status = config('status.接收任务_已结算');
        $receive->save();
        TaskModel::where('id', $task_id)->setInc('finish');
        //判断任务是否完成
        TaskService::isFinish($task_id);
        //任务分红
        TaskService::reward($receive_user_id, $task_id);
        return json(['errorCode' => 0, 'msg' => '粉丝确认成功']);
    }

    //任务驳回
    public function rejectFans($id)
    {
        $user_id = UserService::getUserIdByToken();
        $receive = ReceiveModel::get($id);
        if (!$receive) {
            return json(['errorCode' => 1, 'msg' => '任务参数错误']);
        }
        $task_id = $receive['task_id'];
        if (!TaskService::checkUser($task_id, $user_id)) {
            return json(['errorCode' => 1, 'msg' => '这不是您发布的任务']);
        }
        if ($receive['status'] == config('status.接收任务_已结算')) {
            return json(['errorCode' => 1, 'msg' => '该粉丝已结算']);
        }
        if ($receive['status'] == config('status.接收任务_已驳回')) {
            return json(['errorCode' => 1, 'msg' => '该粉丝已驳回']);
        }
        if ($receive['status'] == config('status.接收任务_驳回处理')) {
            return json(['errorCode' => 1, 'msg' => '该粉丝已驳回']);
        }
        $receive->status = config('status.接收任务_已驳回');
        $receive->reject_time = time();
        $receive->save();
        return json(['errorCode' => 0, 'msg' => '粉丝驳回成功']);
    }

    /**
     * 任务刷新
     * @param $task_id
     * @return array|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function refresh($task_id)
    {
        $user_id = UserService::getUserIdByToken();
        $task = TaskModel::get(['id' => $task_id, 'user_id' => $user_id]);
        if (!$task) {
            return json(['errorCode' => 1, 'msg' => '任务不存在']);
        }
        if ($task['status'] == config('status.任务_已完成')) {
            return json(['errorCode' => 1, 'msg' => '任务已结束']);
        }
        $gold = TaskService::refreshNeedGold($task_id, $user_id);
        if ($gold != 0) {
            if (!UserService::checkGoldBalance($user_id, $gold)) {
                return json(['errorCode' => 1, 'msg' => '金币不足']);
            }
            $cond = ['id' => $user_id];
            $res = (new UserModel())->where($cond)->setDec('gold', $gold);
            //金币日志
            $task_no = TaskModel::where('id', $task_id)->value('number');
            $gold_data = [
                'title' => '刷新任务【' . $task_no . '】扣除',
                'user_id' => $user_id,
                'type' => -1,
                'task_id' => $task_id,
                'amount' => $gold,
                'add_time' => time()
            ];
            GoldModel::create($gold_data);
            if ($res == false) {
                return json(['errorCode' => 1, 'msg' => '刷新失败!']);
            }
        }
        //刷新任务时间,
        $res = TaskService::refresh($task_id);
        if (!$res) {
            return json(['errorCode' => 1, 'msg' => '刷新失败']);
        }
        return json(['errorCode' => 0, 'msg' => '刷新成功']);

    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function refreshNeedGold()
    {
        $user_id = UserService::getUserIdByToken();
        $task_id = input('get.task_id');
        $task = TaskModel::get(['id' => $task_id, 'user_id' => $user_id]);
        if (!$task) {
            return josn(['errorCode' => 1, 'msg' => '不能刷新此任务']);
        }
        $gold = TaskService::refreshNeedGold($task_id, $user_id);
        return json(['errorCode' => 0, 'data' => $gold]);
    }
}